<template>
  <section class="decoration-edit">
    <section class="left">
      <el-card shadow="never" class="box-card">
        <template #header> 组件库 </template>
        <div class="card-default">
          <el-tabs v-model="activeName" class="demo-tabs" @tab-change="tabChange">
            <el-tab-pane label="首页" name="first">
              <div class="group" v-for="unit in typeList" :key="unit.title">
                <div v-if="unit.isShow">
                  <div class="title">{{ unit.title }}</div>
                  <el-row :gutter="10">
                    <el-col :span="8" v-for="(val, index) in unit.comList" :key="index + 1">
                      <div
                        class="grid-content"
                        @dragstart="dragStart($event, val)"
                        @dragend="dragEnd($event, val)"
                        @click="onClick(val)"
                        v-if="val.isShow"
                        :data-name="val.name"
                        :draggable="val.isDraggable"
                      >
                        <el-icon><component :is="val.icon" /></el-icon>
                        <el-text class="mt8" size="small">{{ val.text }}</el-text>
                      </div>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </el-tab-pane>
            <!-- 点餐页面配置start -->
            <el-tab-pane label="点餐页面" name="second">
              <div class="group" v-for="unit in classList" :key="unit.title">
                <div v-if="unit.isShow">
                  <div class="title">{{ unit.title }}</div>
                  <el-row :gutter="10">
                    <el-col :span="8" v-for="(val, index) in unit.comList" :key="index + 1">
                      <div
                        class="grid-content"
                        @dragstart="dragStart($event, val)"
                        @dragend="dragEnd($event, val)"
                        @click="onClick(val)"
                        v-if="val.isShow"
                        :data-name="val.name"
                        :draggable="val.isDraggable"
                      >
                        <el-icon><component :is="val.icon" /></el-icon>
                        <el-text class="mt8" size="small">{{ val.text }}</el-text>
                      </div>
                    </el-col>
                  </el-row>
                </div>
              </div>
              <!-- 点餐页面 end -->
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-card>
      <div class="submit-btn">
        <el-button @click="submit" type="primary">保存</el-button>
      </div>
    </section>
    <!-- 中间显示数据 -->
    <section class="preview pointer" ref="imageTofile" id="imageTofile">
      <div class="top-nav">
        <img :draggable="false" src="@/assets/images/topNavBlack.png" />
      </div>
      <!-- force-fallback忽略h5自定义的拖动样式。配合hostClass chosenClass dragClass自定义样式 -->
      <section
        v-if="activeName === 'first'"
        class="phone-container"
        @drop="drop($event)"
        @dragover="allowDrop($event)"
        @dragleave="dragleave"
      >
        <Draggable :list="datas.pageComponents" item-key="index" :force-fallback="true" :animation="200">
          <template #item="{ element, index }">
            <component
              :is="element.component"
              :datas="element.setStyle"
              :style="{
                border: element.active ? '2px dashed var(--el-color-primary)' : ''
              }"
              @click="activeComponent(element, index)"
              class="componentsClass"
              :data-type="element.type"
            >
              <template #deles>
                <div v-show="element.active" class="deles" @click.stop="deleteObj(index)">
                  <!-- 删除组件 -->
                  <el-tag size="small" type="danger">删除</el-tag>
                </div>
              </template>
            </component>
          </template>
        </Draggable>
      </section>
      <section v-else>
        <!-- 点餐页 -->
        <el-image
          v-if="choose.rightcom === 'ClassifyConfigStyle'"
          style="width: 100%; height: 720px"
          :src="!classifyConfigData.setStyle.linkType ? oneImage : gridImage"
          alt=""
        />

        <!-- 点餐页面组件start -->
        <component style="height: 720px" v-else :is="clickData.component" :datas="clickData.setStyle"></component>

        <!-- 点页面数据end -->
      </section>
    </section>
    <!-- 右侧数据 -->
    <section class="right">
      <component
        :is="choose.rightcom"
        :datas="choose.currentproperties"
        @componenmanagement="componenmanagement"
        @check-type="changeType"
        @classify-config="onClassifyConfig"
      />
    </section>
  </section>
</template>

<script setup lang="ts" name="designPage">
import { ref, reactive, watch, onMounted } from "vue";
import { deepClone } from "@/utils/index"; // 方法类，深拷贝
import Draggable from "vuedraggable"; // 拖拽
import componentProperties from "@/utils/componentProperties"; // 组件数据
import { doDesign, getDesignPageData, getHomePageTemplate } from "@/api/modules/system";
import { ElMessage } from "element-plus";
// import { useUserStore } from "@/stores/modules/user";
import { useRoute } from "vue-router";
import oneImage from "@/assets/images/oneMode.png";
import gridImage from "@/assets/images/gridImage.png";

// const userStore = useUserStore();
const route = useRoute();
// 左侧按钮操作栏数据
const typeList = ref([
  {
    title: "媒体组件",
    isShow: true,
    comList: [
      { icon: "CopyDocument", isDraggable: true, type: "1-1", isShow: true, text: "图片轮播", name: "ImgSlide" },
      { icon: "CopyDocument", isDraggable: true, type: "1-2", isShow: true, text: "图片", name: "ImgSingle" },
      { icon: "CopyDocument", isDraggable: true, type: "1-3", isShow: true, text: "图片分组", name: "ImgWindow" },
      { icon: "CopyDocument", isDraggable: true, type: "1-4", isShow: true, text: "视频组", name: "Videos" }
    ]
  },
  {
    title: "商城组件",
    isShow: route.query.pageCode === "mobile_food" ? false : true,
    // isShow: true,
    comList: [
      { icon: "CopyDocument", isDraggable: true, type: "2-1", isShow: true, text: "搜索框", name: "Search" },
      { icon: "CopyDocument", isDraggable: true, type: "2-2", isShow: true, text: "公告组", name: "Notice" },
      { icon: "CopyDocument", isDraggable: true, type: "2-3", isShow: true, text: "导航组", name: "NavBar" },
      { icon: "CopyDocument", isDraggable: true, type: "2-4", isShow: true, text: "商品组", name: "Goods" },
      { icon: "CopyDocument", isDraggable: true, type: "2-5", isShow: true, text: "商品选项卡", name: "GoodTabBar" },
      { icon: "CopyDocument", isDraggable: true, type: "2-6", isShow: true, text: "团购", name: "GroupPurchase" },
      { icon: "CopyDocument", isDraggable: true, type: "2-7", isShow: true, text: "秒杀", name: "Seckill" },
      { icon: "CopyDocument", isDraggable: true, type: "2-8", isShow: true, text: "拼团", name: "PinTuan" },
      { icon: "CopyDocument", isDraggable: true, type: "2-9", isShow: true, text: "优惠券", name: "Coupon" }
    ]
  },
  {
    title: "工具组件",
    isShow: true,
    comList: [
      { icon: "CopyDocument", isDraggable: true, type: "3-1", isShow: true, text: "辅助空白", name: "Blank" },
      { icon: "CopyDocument", isDraggable: true, type: "3-2", isShow: true, text: "文本域", name: "TextArea" },
      {
        icon: "CopyDocument",
        type: "3-3",
        isShow: !route.query.pageCode == "mobile_food" ? false : true,
        text: "登录",
        name: "Login",
        isDraggable: true
      }
    ]
  },
  {
    title: "首页模版设计",
    isShow: true,
    comList: [
      {
        icon: "CopyDocument",
        isDraggable: false,
        type: "4-1",
        isShow: true,
        isClick: true,
        text: "首页模版",
        name: "HomePageTemplate"
      }
    ]
  },
  {
    title: "营销配置",
    isShow: true,
    comList: [
      // { icon: "CopyDocument", isDraggable: true, type: "5-1", isShow: true, text: "弹出广告", name: "PopupImage" },
      { icon: "CopyDocument", isDraggable: true, type: "5-2", isShow: true, text: "特价活动栏", name: "AdvertisingColumn" }
    ]
  }
]);

const classList = ref([
  {
    title: "点餐页配置",
    isShow: true,
    comList: [
      {
        icon: "CopyDocument",
        isDraggable: false,
        type: "4-2",
        isShow: true,
        isClick: true,
        text: "点餐页",
        name: "ClassifyConfig"
      },
      {
        icon: "CopyDocument",
        isDraggable: false,
        type: "4-3",
        isShow: true,
        isClick: true,
        text: "人数页",
        name: "DeskConfig"
      }
    ]
  }
]);

// tabs默认选项
const activeName = ref("first");

// 中间页面数据
const datas = reactive({
  id: null, //当前页面id
  pageSetup: {
    // 页面设置属性
    name: "页面标题", //页面名称
    details: "", //页面描述
    isPerson: false, // 是否显示个人中心
    isBack: true, // 是否返回按钮
    titleHeight: 35, // 高度
    bgColor: "rgba(249, 249, 249, 10)", //背景颜色
    bgImg: "" // 背景图片
  },
  pageComponents: [] //页面组件
});

// 选择组件数据
const choose = reactive({
  deleShow: false, // 删除标签显示
  index: "", // 当前选中的index
  rightcom: "decorate", // 右侧组件切换
  currentproperties: datas.pageSetup, // 当前属性  默认：页面设置
  offsetY: 0, //记录上一次距离父元素高度
  onlyOne: ["1-5", "1-16"], // 只能存在一个的组件(组件的type)
  pointer: { show: false } // 穿透
});

// 拖拽类型
const dragStart = (event: any, val: any) => {
  choose.pointer.show = true;
  event.dataTransfer.setData("componentName", event.target.dataset.name);
};
// 结束拖拽
const dragEnd = () => {
  choose.pointer.show = false;
};

// 删除组件
const deleteObj = index => {
  datas.pageComponents.splice(index, 1);
  if (choose.index === index) choose.rightcom = "decorate";
  if (index < choose.index) choose.index = choose.index - 1;
};
// 选中的样式
const activeComponent = (res, index) => {
  choose.index = index;
  /* 切换组件 */
  choose.rightcom = res.style;
  /* 丢样式 */
  choose.currentproperties = res.setStyle;

  /* 替换 */
  datas.pageComponents.forEach(res => {
    /* 修改选中 */
    if (res.active) res.active = false;
  });

  /* 选中样式 */
  res.active = true;
};

//  当在有效放置目标上放置元素或选择文本时触发此事件

// 放在中间盒子的数据
const drop = (event: any) => {
  /* 获取数据 */
  let data = deepClone(componentProperties.get(event.dataTransfer.getData("componentName")));
  /* 替换 */

  datas.pageComponents.forEach((res, index) => {
    /* 修改选中 */
    if (res.active === true) res.active = false;
    /* 替换提示 */
    choose.index = index;
    if (res.component === "PlaceMentArea") datas.pageComponents[index] = data;
  });

  /* 切换组件 */
  choose.rightcom = data.style;
  /* 丢样式 */
  choose.currentproperties = data.setStyle;
};

const allowDrop = (event: Event) => {
  //阻止浏览器的默认事件
  event.preventDefault();
  if (datas.pageComponents.length) {
    datas.pageComponents = datas.pageComponents.filter(res => res.component !== "PlaceMentArea");
    datas.pageComponents.push({
      component: "PlaceMentArea",
      type: 0
    });
  } else {
    datas.pageComponents.push({
      component: "PlaceMentArea",
      type: 0
    });
  }
};
const dragleave = () => {
  /* 删除提示组件 */
  datas.pageComponents = datas.pageComponents.filter(res => res.component !== "PlaceMentArea");
};

// 监听右侧属性设置切换
watch(
  () => choose.rightcom,
  newval => {
    if (newval === "decorate") {
      datas.pageComponents.forEach(res => {
        /* 修改选中 */
        if (res.active === true) res.active = false;
      });
      choose.currentproperties = datas.pageSetup;
      return;
    }
    if (newval === "componenmanagement") {
      /* 替换 */
      datas.pageComponents.forEach(res => {
        /* 修改选中 */
        if (res.active === true) res.active = false;
      });
      choose.currentproperties = datas.pageComponents;
    }
  }
);
const componenmanagement = res => {
  datas.pageComponents = res;
};
// 获取页面数据
const getPageData = () => {
  getDesignPageData({ ...route.query }).then(res => {
    classifyConfigData.value = res.data.classifyConfigData;
    canteenConfig.value = res.data.canteenConfig;
    // DeskConfigData.value = res.data.DeskConfigData
    if (res.data.pageConfig.length > 0) {
      datas.pageComponents = res.data.pageConfig.map(im => {
        return {
          component: im.type,
          style: im.type + "Style",
          setStyle: im.value
        };
      });
    }
  });
};

onMounted(() => {
  getPageData();
});

// 提交页面数据
const submit = () => {
  doDesign({
    datalist: datas.pageComponents.map(im => {
      return {
        sType: im.component,
        sValue: JSON.stringify({ ...im.setStyle })
      };
    }),
    pageCode: route.query.pageCode,
    classifyConfigData: classifyConfigData.value,
    canteenConfig: canteenConfig.value
  }).then(res => {
    ElMessage({
      message: res.msg,
      type: "success"
    });
  });
};

/* 点餐页面配置start */
const classifyConfigData = ref<any>({}); // 点餐页面数据
const canteenConfig = ref<{}>({}); // 点餐页面数据后面配的数据

// 点击全部展示的页面数据
interface ClickData {
  component: string;
  text: string;
  type: string;
  active: boolean;
  style: string;
  setStyle: any;
}
const clickData = ref<ClickData>({});

// 页面设计不选择拖拽
const checkTypeList = ref<any[]>([]);
const onClick = async (val: any) => {
  console.log(componentProperties.get(val.name));

  if (!val.isClick) return;
  if (val.name === "HomePageTemplate") {
    // 首页模版
    datas.pageComponents = [];
    const res: any = await getHomePageTemplate({});
    activeComponent(res.data, 0);
    checkTypeList.value = res.data;
  } else if (val.name === "ClassifyConfig") {
    // 分类配置
    activeComponent(classifyConfigData.value, 0);
  } else if (val.name === "DeskConfig") {
    activeComponent(canteenConfig.value.deskConfig, 0);
    // clickData.value = componentProperties.get(val.name);
    clickData.value = canteenConfig.value.deskConfig;
  }
};
// 选中索引父传子
function changeType(params: number) {
  datas.pageComponents = checkTypeList.value.setStyle.list[params].itemList.map(im => {
    return {
      component: im.type,
      style: im.type + "Style",
      setStyle: im.value
    };
  });
}

// tabs栏发生改变时触发
const tabChange = (e: string) => {
  console.log(e);
  activeComponent({}, 0);
  if (e === "second") {
    activeComponent(classifyConfigData.value, 0);
  }
};

// 判断是否是点餐页
const onClassifyConfig = (e: any) => {
  submit();
};

/* 点餐页面配置end */
</script>
<style lang="scss" scoped>
.decoration-edit {
  display: flex;
  justify-content: space-between;
  height: 100%;
  .left {
    flex-shrink: 0;
    width: 300px;
    height: 100%;
    overflow-y: auto;
    background-color: #ffffff;
    .box-card {
      border: none;
      .card-default {
        .title {
          margin: 0 0 10px 5px;
          font-size: 12px;
          color: #999999;
        }
        .grid-content {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 14px 0;
          margin-bottom: 10px;
          cursor: pointer;
          background-color: #f5f5f5;
          transition: all 0.3s;
        }
      }
    }
    .submit-btn {
      display: flex;
      flex-direction: row-reverse;
      padding: 20px 20px 0 0;
      border-top: 1px solid #e4e7ed;
    }
  }
  .preview {
    flex-shrink: 0;
    width: 375px;
    overflow: hidden;
    border: 1px solid #e9e9e9;
    box-shadow: 0 3px 10px #dcdcdc;
    .top-nav img {
      display: block;
      width: 100%;
      height: 88px;
      background-color: #ffffff;
    }
    .phone-container {
      height: calc(100% - 88px);

      // overflow: overlay;
      overflow-y: scroll;
      .componentsClass {
        position: relative;
        border: 2px solid #ffffff;
        &:hover {
          border: 2px dashed var(--el-color-primary);
        }
        .deles {
          position: absolute;
          right: 4px;
          bottom: 4px;
        }
      }
    }
  }
  .right {
    width: 360px;
    padding: 20px;
    overflow: overlay;
    background-color: #ffffff;
  }
}
</style>
